export default class ResUtils {

    static loadPrefab(path: string, successCallback: Function, errorCallback?: Function) {
        if (path.indexOf('prefabs') < 0) {
            path = 'prefabs/' + path;
        }
        ResUtils.loadType(path, cc.Prefab, successCallback, errorCallback);
    }

    static loadSpriteFrame(path: string, successCallback: Function, errorCallback?: Function) {
        if (path.indexOf('textures') < 0) {
            path = 'textures/' + path;
        }
        ResUtils.loadType(path, cc.SpriteFrame, successCallback, errorCallback);
    }

    static loadSpriteAtlas(path: string, successCallback: Function, errorCallback?: Function) {
        if (path.indexOf('textures') < 0) {
            path = 'textures/' + path;
        }
        ResUtils.loadType(path, cc.SpriteAtlas, successCallback, errorCallback);
    }

    static loadAudio(path: string, successCallback: Function, errorCallback?: Function) {
        if (path.indexOf('audios') < 0) {
            path = 'audios/' + path;
        }
        ResUtils.loadType(path, cc.AudioClip, successCallback, errorCallback);
    }

    static loadJSON(path: string, successCallback: Function, errorCallback?: Function) {
        if (path.indexOf('configs') < 0) {
            path = 'configs/' + path;
        }
        ResUtils.loadType(path, cc.JsonAsset, (res)=>{
            if(successCallback){
                successCallback(res.json);
            }
        }, errorCallback);
    }

    static loadType(path: string, type: typeof cc.Asset, successCallback: Function, errorCallback?: Function) {
        cc.loader.loadRes(path, type, (err, res) => {
            if (err) {
                console.error(err);
                console.error('[path: ' + path + ']');
                if (errorCallback) {
                    errorCallback(err);
                }
                return;
            }
            if (successCallback) {
                successCallback(res);
            }
        });
    }

}
